package com.zou.application.controller.customer;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zou.application.dao.BankCarEntityMapper;
import com.zou.application.dao.OrderEntityMapper;
import com.zou.application.dao.ShopCarEntityMapper;
import com.zou.application.dao.TranstacRecordEntityMapper;
import com.zou.application.dao.UserEntityMapper;
import com.zou.application.entity.BankCarEntity;
import com.zou.application.entity.OrderEntity;
import com.zou.application.entity.ShopCarEntity;
import com.zou.application.entity.TranstacRecordEntity;
import com.zou.application.entity.UserEntity;
import com.zou.application.utils.RandomUtils;

@Controller
@RequestMapping("/order")
public class OrderController {
	
	@Autowired
	private OrderEntityMapper orderDao;
	@Autowired
	private UserEntityMapper userEntityMapper;
	@Autowired
	private ShopCarEntityMapper shopCarDao;
	@Autowired
	private BankCarEntityMapper bankDao;
	@Autowired
	private TranstacRecordEntityMapper transtacDao;
	
	@RequestMapping("/addOrder")
	@ResponseBody
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public JSONObject addOrder(HttpSession session,HttpServletRequest request){
		JSONObject result = new JSONObject();
		Integer userId = (Integer) session.getAttribute("userId");
		String carIds = request.getParameter("carIds");
		JSONArray jsonCarIds = JSONArray.parseArray(carIds);
		if(userId == null){
			result.put("code","100");
			result.put("message","用户名不能为空");
		}
		try {
			OrderEntity orderEntity = new OrderEntity();
			for(Object item : jsonCarIds){
				JSONObject param = (JSONObject) item;
				ShopCarEntity shopCarEntity = shopCarDao.selectById(param.getInteger("carId"));
				UserEntity user = userEntityMapper.selectById(userId);
				orderEntity.setCreater(user.getName());
				orderEntity.setCreateTime(new Date());
				orderEntity.setOrderAddress(shopCarEntity.getReceiveAddress());
				orderEntity.setOrderCode(RandomUtils.randomString(5)+RandomUtils.randomNumber(8));
				orderEntity.setProductNumber(jsonCarIds.size());
				if(orderEntity.getCountMoney() != null){
					orderEntity.setOrderMoney(shopCarEntity.getRelPrice().add(orderEntity.getCountMoney()));
					orderEntity.setDiscountMoney(shopCarEntity.getDiscountPrice().add(orderEntity.getDiscountMoney()));
					orderEntity.setCountMoney(shopCarEntity.getCountProce().add(orderEntity.getOrderMoney()));
					orderEntity.setProductName(shopCarEntity.getProductName()+" , "+orderEntity.getProductName());
				}else{
					orderEntity.setOrderMoney(shopCarEntity.getRelPrice());
					orderEntity.setDiscountMoney(shopCarEntity.getDiscountPrice());
					orderEntity.setCountMoney(shopCarEntity.getCountProce());
					orderEntity.setProductName(shopCarEntity.getProductName());
				}
				orderEntity.setStatus((short)1);
				orderEntity.setIsDelete((short)0);
				orderEntity.setOrderUserId(userId);
				shopCarEntity.setStatus((short)2);
				shopCarDao.update(shopCarEntity);
			}
			orderDao.insert(orderEntity);
			result.put("code", "200");
			result.put("msg", "提交订单成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "200");
			result.put("msg", "提交订单失败");
		}
		return result;
	}
	
	/**
	 * 查看订单详情
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/viewOrder")
	public ModelAndView viewOrder(HttpSession session,HttpServletRequest request){
		ModelAndView mv = new ModelAndView("/customer/view_order");
		String orderId = request.getParameter("orderId");
		try {
			OrderEntity orderEntity = orderDao.selectById(Integer.valueOf(orderId));
			mv.addObject("order", orderEntity);
			mv.addObject("code", "200");
			mv.addObject("msg", "查看成功");
		} catch (Exception e) {
			e.printStackTrace();
			mv.addObject("code", "100");
			mv.addObject("msg", "失败");
		}
		return mv;
	}
	
	@RequestMapping("/deleteOrder")
	@ResponseBody
	public JSONObject deleteOrder(HttpSession session,HttpServletRequest request){
		JSONObject result = new JSONObject();
		Integer userId = (Integer) session.getAttribute("userId");
		if(userId == null){
			result.put("code","100");
			result.put("message","用户名不能为空");
			return result;
		}
		String orderId = request.getParameter("orderId");
		try {
			orderDao.delete(Integer.valueOf(orderId));
			result.put("code", "200");
			result.put("msg", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "100");
			result.put("msg", "删除失败");
		}
		return result;
	}
	
	@RequestMapping("/cancleOrder")
	@ResponseBody
	public JSONObject cancleOrder(HttpSession session,HttpServletRequest request){
		JSONObject result = new JSONObject();
		Integer userId = (Integer) session.getAttribute("userId");
		if(userId == null){
			result.put("code","100");
			result.put("message","用户名不能为空");
		}
		String orderId = request.getParameter("orderId");
		try {
			UserEntity userEntity = new UserEntity();
			userEntity=userEntityMapper.selectById(userId);
			OrderEntity orderEntity =new OrderEntity();
			orderEntity.setId(Integer.valueOf(orderId));
			orderEntity.setModifier(userEntity.getUserName());
			orderEntity.setModifyTime(new Date());
			orderEntity.setStatus((short)3);
			orderDao.update(orderEntity);
			result.put("code", "200");
			result.put("msg", "取消成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", "100");
			result.put("msg", "删除失败");
		}
		return result;
	}
	
	/**
	 * 支付订单
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/payOrder")
	@ResponseBody
	@Transactional(propagation=Propagation.REQUIRED)
	public JSONObject payOrder(HttpSession session,HttpServletRequest request){
		JSONObject result = new JSONObject();
		Integer userId = (Integer) session.getAttribute("userId");
		if(userId == null){
			result.put("code","100");
			result.put("message","用户名不能为空");
		}
		String orderId = request.getParameter("orderId");
		UserEntity userEntity = new UserEntity();
		userEntity=userEntityMapper.selectById(userId);
		OrderEntity orderEntity = orderDao.selectById(Integer.valueOf(orderId));
		orderEntity.setId(Integer.valueOf(orderId));
		orderEntity.setModifier(userEntity.getUserName());
		orderEntity.setModifyTime(new Date());
		orderEntity.setStatus((short)2);
		orderDao.update(orderEntity);
		BankCarEntity bankCar = bankDao.selectByUserId(userId);
		bankCar.setBankMoney(bankCar.getBankMoney().subtract(orderEntity.getCountMoney()));
		bankDao.update(bankCar);
		TranstacRecordEntity transtacRecor = new TranstacRecordEntity();
		transtacRecor.setOrderCode(orderEntity.getOrderCode());
		transtacRecor.setOrderId(orderEntity.getId());
		transtacRecor.setPayMoney(orderEntity.getCountMoney());
		transtacRecor.setProductMoney(orderEntity.getOrderMoney());
		transtacRecor.setCreater(userEntity.getUserName());
		transtacRecor.setCreateTime(new Date());
		int id = transtacDao.insert(transtacRecor);
		result.put("code", "200");
		result.put("msg", "支付成功");
		if(id == 0){
			result.put("code", "100");
			result.put("msg", "删除失败");
		}
		return result;
	}
	
	@RequestMapping("/orderList")
	public ModelAndView orderList(HttpServletRequest request,HttpSession session){
		ModelAndView mv = new ModelAndView();
		Integer userId = (Integer) session.getAttribute("userId");
		if(userId == null){
			mv.addObject("code","100");
			mv.addObject("message","用户名不能为空");
		}
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			param.put("status", 1);
			List<OrderEntity> orderEntities = orderDao.listByMap(param);
			mv.addObject("orders",orderEntities);
			mv.setViewName("/customer/unpay_order_list");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	@RequestMapping("/payOrderList")
	public ModelAndView payOrderList(HttpServletRequest request,HttpSession session){
		ModelAndView mv = new ModelAndView();
		Integer userId = (Integer) session.getAttribute("userId");
		if(userId == null){
			mv.addObject("code","100");
			mv.addObject("message","用户名不能为空");
		}
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("userId", userId);
			param.put("status", 2);
			List<OrderEntity> orderEntities = orderDao.listByMap(param);
			mv.addObject("orders",orderEntities);
			mv.setViewName("/customer/pay_order_list");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}
}